//基本计算器 II
//测试链接 https://leetcode.cn/problems/basic-calculator-ii/
public class Calculate {
    public int[] stack = new int[200000];
    public int calculate(String s) {
        int pos = 0; //栈的位置
        char[] arr = s.toCharArray();
        int n = arr.length;

        char op = '+'; //初始符号为+号
        int i = 0;
        while(i < n) {
            char ch = arr[i];
            if(ch == ' ') i++;  //遇到空格直接跳过
                //遇到数字
            else if(arr[i] >= '0' && arr[i] <= '9' ) {
                //获取完整数字
                int num = 0;
                while(i < n && arr[i] >= '0' && arr[i] <= '9') {
                    num = num * 10 + ( arr[i] - '0' );
                    i++;
                }
                //查询当前数字之前的符号
                if(op == '+') stack[pos++] = num;
                else if(op == '-') stack[pos++] = -num;
                else if(op == '*') stack[pos-1] = stack[pos - 1] * num;
                else stack[pos-1] = stack[pos - 1] / num;
            }
            //遇到的是符号
            else{
                op = ch;
                i++;
            }
        }

        int ret = 0;
        for(i = 0; i < pos; i++){
            ret += stack[i];
        }

        return ret;
    }
}
